package controllers

import (
	"fmt"
	"gindemo02/models"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/patrickmn/go-cache"
	"golang.org/x/crypto/bcrypt"
)

type LoginController struct {
	BaseController
	CacheCode *cache.Cache
}

// 执行用户登录操作
func (con LoginController) Index(c *gin.Context) {
	var loginData struct {
		Mobile   string `json:"mobile" binding:"required"`
		Password string `json:"password,omitempty" `
		Code     string `json:"code,omitempty"`
	}

	// 绑定请求数据到loginData变量
	if err := c.ShouldBindJSON(&loginData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 40101, "msg": "传入的变量数据错误", "error": err.Error()})
		return
	}

	// 查询数据库中是否存在该账号
	var account models.Account
	if err := models.DB.Where("mobile = ?", loginData.Mobile).First(&account).Error; err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"code": 40102, "msg": "账号不存在", "error": "Invalid credentials"})
		return
	}

	// 如果密码字段存在则添加密码
	if account.Password != "" {
		// 验证密码是否匹配
		if err := bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(loginData.Password)); err == nil {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 40107, "msg": "账号密码错误", "error": "Invalid credentials"})
			return
		}
	}
	//用于验证验证码是否正确
	// cacheCode, _ := c.Get("CacheCode")
	// CacheCode := cacheCode.(*cache.Cache)
	// if code, found := CacheCode.Get(account.Mobile); found {
	// 	if code != account.Code {
	// 		c.JSON(http.StatusOK, gin.H{"code": 40108, "msg": "验证码错误"})
	// 		return
	// 	}
	// } else {
	// 	c.JSON(http.StatusOK, gin.H{"code": 40109, "msg": "验证码错误或不能为空"})
	// 	return
	// }

	tokenString, _ := models.GenerateToken(account.Id, account.Mobile, 6, "qinuoyun")

	refreshToken, _ := models.GenerateToken(account.Id, account.Mobile, 72, "qinuoyun")

	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "创建成功", "token": tokenString, "data": account, "refreshToken": refreshToken})
}

// 执行用户注册操作
func (con LoginController) Signup(c *gin.Context) {
	// 绑定注册请求的JSON数据到account结构体
	var account models.Account
	if err := c.ShouldBindJSON(&account); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 查询数据库中是否已存在相同手机号的用户
	var existingUser models.Account
	if err := models.DB.Where("mobile = ?", account.Mobile).First(&existingUser).Error; err == nil {
		c.JSON(http.StatusConflict, gin.H{"code": 40103, "msg": "已注册手机号", "error": "Mobile number already registered"})
		return
	}

	//用于验证验证码是否正确
	cacheCode, _ := c.Get("CacheCode")
	CacheCode := cacheCode.(*cache.Cache)
	if code, found := CacheCode.Get(account.Mobile); found {
		if code != account.Code {
			c.JSON(http.StatusOK, gin.H{"code": 40108, "msg": "验证码错误"})
			return
		}
	} else {
		c.JSON(http.StatusOK, gin.H{"code": 40109, "msg": "验证码错误或不能为空"})
		return
	}

	// 创建用户并保存到数据库
	newUser := models.Account{
		Mobile: account.Mobile,
	}

	// 如果密码字段存在则添加密码
	if account.Password != "" {
		// 对密码进行加密
		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(account.Password), bcrypt.DefaultCost)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"code": 40104, "msg": "密码错误", "error": "Failed to hash password"})
			return
		}

		// 创建用户并保存到数据库
		newUser.Password = string(hashedPassword)

	}

	fmt.Println("打印用户细腻", newUser)

	if err := models.DB.Create(&newUser).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 40106, "msg": "无法创建账户", "error": "Failed to create user"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "创建成功"})
}

// 执行用户注册操作
func (con LoginController) Code(c *gin.Context) {
	//获取缓存方法
	cacheCode, _ := c.Get("CacheCode")
	CacheCode := cacheCode.(*cache.Cache)
	//获取手机号并调用发送接口
	Mobile := c.Query("mobile")
	Code := models.GenerateCode()
	fmt.Println("查看验证码:", Code)
	CacheCode.Set(Mobile, Code, cache.DefaultExpiration)
	//models.VerificationCode(Mobile, Code)
	//打印发送的验证码
	fmt.Println("cacheCode-code"+Mobile, Code)
	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "验证码以发送"})
}

// 执行用户注册操作
func (con LoginController) Demo(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "测试接口", "data": 1})
}
